package com.clouduserservice8001.service.impl;

import com.clouduserservice8001.entity.User;
import com.clouduserservice8001.mapper.UserMapper;
import com.clouduserservice8001.service.UserService;
import com.clouduserservice8001.util.PasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户服务实现类
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Override
    public User login(String userId, String password) {
        // 根据用户ID查询用户
        User user = userMapper.selectByUserId(userId);
        if (user == null) {
            return null; // 用户不存在
        }
        
        // 检查用户状态
        if (!"1".equals(user.getStatus())) {
            return null; // 用户已禁用
        }
        
        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            return null; // 密码错误
        }
        
        // 更新最后登录时间
        userMapper.updateLastLoginTime(userId, LocalDateTime.now());
        
        // 清除密码信息后返回
        user.setPassword(null);
        return user;
    }
    
    @Override
    public boolean createUser(User user, String createBy) {
        // 检查用户ID是否已存在
        if (isUserIdExists(user.getUserId())) {
            return false;
        }
        
        // 加密密码
        if (user.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        
        // 设置创建信息
        user.setCreateBy(createBy);
        user.setCreateTime(LocalDateTime.now());
        user.setStatus("1"); // 默认启用
        
        // 设置默认用户类型
        if (user.getUserType() == null) {
            user.setUserType("user");
        }
        
        return userMapper.insert(user) > 0;
    }
    
    @Override
    public boolean updateUser(User user, String updateBy) {
        // 先根据userId查询现有用户信息，获取id字段
        User existingUser = userMapper.selectByUserId(user.getUserId());
        if (existingUser == null) {
            return false; // 用户不存在
        }

        // 设置主键ID
        user.setId(existingUser.getId());

        // 设置更新信息
        user.setUpdateBy(updateBy);
        user.setUpdateTime(LocalDateTime.now());

        // 如果有密码，需要加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        } else {
            // 如果没有提供密码，保持原密码不变
            user.setPassword(null);
        }

        return userMapper.updateByPrimaryKeySelective(user) > 0;
    }
    
    @Override
    public boolean deleteUser(String userId, String updateBy) {
        // 逻辑删除：设置状态为禁用
        return updateUserStatus(userId, "0", updateBy);
    }
    
    @Override
    public boolean updateUserStatus(String userId, String status, String updateBy) {
        return userMapper.updateStatus(userId, status, updateBy, LocalDateTime.now()) > 0;
    }
    
    @Override
    public boolean changePassword(String userId, String oldPassword, String newPassword, String updateBy) {
        // 验证旧密码
        User user = userMapper.selectByUserId(userId);
        if (user == null || !passwordEncoder.matches(oldPassword, user.getPassword())) {
            return false;
        }
        
        // 更新新密码
        String encodedNewPassword = passwordEncoder.encode(newPassword);
        return userMapper.updatePassword(userId, encodedNewPassword, updateBy, LocalDateTime.now()) > 0;
    }
    
    @Override
    public boolean resetPassword(String userId, String newPassword, String updateBy) {
        String encodedNewPassword = passwordEncoder.encode(newPassword);
        return userMapper.updatePassword(userId, encodedNewPassword, updateBy, LocalDateTime.now()) > 0;
    }
    
    @Override
    public User getUserByUserId(String userId) {
        User user = userMapper.selectByUserId(userId);
        if (user != null) {
            user.setPassword(null); // 清除密码信息
        }
        return user;
    }
    
    @Override
    public List<User> getUsersByType(String userType) {
        List<User> users = userMapper.selectByUserType(userType);
        // 清除密码信息
        users.forEach(user -> user.setPassword(null));
        return users;
    }
    
    @Override
    public List<User> getAllUsers() {
        List<User> users = userMapper.selectAll();
        // 清除密码信息
        users.forEach(user -> user.setPassword(null));
        return users;
    }
    
    @Override
    public List<User> getUserList(String userType, String status, String keyword) {
        List<User> users = userMapper.selectUserList(userType, status, keyword);
        // 清除密码信息
        users.forEach(user -> user.setPassword(null));
        return users;
    }
    
    @Override
    public boolean isUserIdExists(String userId) {
        return userMapper.countByUserId(userId) > 0;
    }
    
    @Override
    public boolean hasPermission(String userId, String operation) {
        User user = userMapper.selectByUserId(userId);
        if (user == null || !"1".equals(user.getStatus())) {
            return false; // 用户不存在或已禁用
        }
        
        // 极简逻辑：admin、employee和user都有相同权限
        return "admin".equals(user.getUserType()) || 
               "employee".equals(user.getUserType()) || 
               "user".equals(user.getUserType());
    }
}
